import db from '~~/DB';
import { validateMenu } from '~~/mocks/middleware/menu';

export default validateMenu('system-role', async (req, res, ctx) => {
  const key = req.url.searchParams.get('key') || '';
  let keys = req.url.searchParams.getAll('key') || [];
  const title = req.url.searchParams.get('title') || '';
  const status = req.url.searchParams.get('status');
  const page = Number(req.url.searchParams.get('page') || 1);
  const pageSize = Number(req.url.searchParams.get('pageSize') || 10);
  const table = db.roles;

  if (!key) {
    // key==='', keys===['']
    keys = [];
  }

  let collection = table.filter(
    (v) =>
      (keys.length ? keys.includes(v.key) : true) &&
      (title ? v.title.includes(title) : true) &&
      (status ? v.status === Number(status) : true),
  );

  const total = await collection.count();
  const users = await collection
    .offset(pageSize * (page - 1))
    .limit(pageSize)
    .toArray();

  return res(
    ctx.json({
      list: users.map((v) => ({ ...v, password: undefined })),
      total,
    }),
  );
  // status &&
  //   (collection = collection.filter(
  //     (value) => value.status === Number(status),
  //   ));
});
